//
//  deskShowCollectionViewController.m
//  BeautyPicture
//
//  Created by 沈振邦 on 15/8/5.
//  Copyright (c) 2015年 szb. All rights reserved.
//

#import "BPProductInfoViewController.h"
#import "BPProductMakeViewController.h"
#import "BPProductInfoCell.h"
#import "ImageAddPreView.h"
#import "AppDelegate.h"
#import "BPProductTool.h"
#import "BPProductDetail.h"
#import "MJExtension.h"
#import "BPImageTool.h"
#import "NavView.h"
#import "PagedetailData.h"
#import "UIImageView+WebCache.h"
#import "SDImageCache.h"
#import "ShowPicture.h"
#import "iCarousel.h"
#import "PageS.h"


#define ImageCahes [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject]

@interface BPProductInfoViewController ()<navDelegate,ImageAddPreViewDelegate,UICollectionViewDelegateFlowLayout,UICollectionViewDelegate,UICollectionViewDataSource>
{
    UIView *_rootView;
}

/** 用来存放整个台历的信息*/
@property (nonatomic,strong)BPProductDetail *productDetailModel;

@property (nonatomic,strong)AppDelegate *delegate;

@property (nonatomic,strong)NSMutableArray *picArry;

@property (nonatomic, assign) CGFloat offHeigt;
@property (nonatomic, assign) CGFloat offWidth;

@property (nonatomic, strong) UIButton *buttonGame;
@property (nonatomic, strong) UIButton *buttonNextOne;
@property (nonatomic, strong) UIButton *buttonCity;
@property (nonatomic, strong) UIButton *cityName;

@property (nonatomic, assign) unsigned long Sum;
@property (nonatomic, strong) BPProductMakeViewController *meituEditVC;

@end

@implementation BPProductInfoViewController

- (void)viewWillAppear:(BOOL)animated
{
    if (_delegate.backHome == YES) {
        [self.navigationController popToRootViewControllerAnimated:YES];
        _delegate.backHome = NO;
    }
    self.navigationController.navigationBarHidden = YES;
}

- (void)viewWillDisappear:(BOOL)animated{
    self.navigationController.navigationBarHidden = NO;
}

// 隐藏顶部的状态栏
- (BOOL)prefersStatusBarHidden {
    
    return YES;
}

- (void)downLoadProductInfo
{
    
    [BPProductTool prodectDetailDataWithProductID:self.prodectInfo.iD success:^(BPProductDetail *result) {
        
        [[NSUserDefaults standardUserDefaults] setObject:result.pages forKey:@"pages"];
        [[NSUserDefaults standardUserDefaults] synchronize];
        
        //1.更新数据
        [_detailDataManger deleteProductDetail:self.prodectInfo.iD];
        [_detailDataManger insertProductDetail:result];
        
        //1.数据处理
        _productDetailModel = [self makeDataToModel:result];
        //2.更新UI
        [_headView addProductData:result];
        [_detailModelShow reloadData];
        
        [self getShowPicArry];
    
    } failure:^(NSError *error) {
        [_detailDataManger deleteProductDetail:self.prodectInfo.iD];
        BPLog(@"网络错误");
    }];
}

- (BPProductDetail *)makeDataToModel:(BPProductDetail *)detailPage
{
    if (_productDetailModel.is_promot == 0) {
        detailPage.finalPrice = detailPage.price;
    }else
    {
        detailPage.finalPrice = detailPage.promotion_price;
    }
    detailPage.category = self.leftNavButton;
    detailPage.title = self.prodectInfo.title;
    
    
    
    //取出产品中每页的信息，转化成对象放在数组
    detailPage.pages = [BPProductDetailPage objectArrayWithKeyValuesArray:detailPage.pages];
    
    
    //遍历数组，获取每页产品的信息，再获取每页产品信息中的model数组
    for (BPProductDetailPage *page in detailPage.pages) {
        if (![page.moulds isKindOfClass:[NSNull class]] && page.moulds != nil) {
            page.moulds = [BPProductModel objectArrayWithKeyValuesArray:page.moulds];
        }
    }
    return detailPage;
}

- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    self.offHeigt = [[UIScreen mainScreen]bounds].size.height / 667;
    self.offWidth = [[UIScreen mainScreen]bounds].size.width / 375;
    
    [self setBaseData];
    
    //[self setUpNav];
    //设置ui
    [self setUpdeskCollectionView];
    
    [self createButton];
}


// 创建 返回按钮
- (void)createButton{
    
    
    UIButton *buttonBig = [[UIButton alloc] initWithFrame:CGRectMake(20, 25, 80, 50)];
    buttonBig.backgroundColor = [UIColor clearColor];
    [buttonBig addTarget:self action:@selector(button:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:buttonBig];
    
    UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 23, 23)];
    [button setBackgroundImage:[UIImage imageNamed:@"返回"] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(button:) forControlEvents:UIControlEventTouchUpInside];
    [buttonBig addSubview:button];
    
//    UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(20, 25, 23, 23)];
//    [button setBackgroundImage:[UIImage imageNamed:@"返回"] forState:UIControlStateNormal];
//    [button addTarget:self action:@selector(button:) forControlEvents:UIControlEventTouchUpInside];
//    [self.view addSubview:button];
    
    UIButton *buttonHomeBig = [[UIButton alloc] initWithFrame:CGRectMake(self.view.frame.size.width - 40, 25, 50, 50)];
    buttonHomeBig.backgroundColor = [UIColor clearColor];
    [buttonHomeBig addTarget:self action:@selector(buttonHome:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:buttonHomeBig];
    
    UIButton *buttonHome = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 23, 23)];
    [buttonHome setBackgroundImage:[UIImage imageNamed:@"homeLeft02"] forState:UIControlStateNormal];
    [buttonHome addTarget:self action:@selector(buttonHome:) forControlEvents:UIControlEventTouchUpInside];
    [buttonHomeBig addSubview:buttonHome];
    
//    UIButton *buttonHome = [[UIButton alloc] initWithFrame:CGRectMake(self.view.frame.size.width - 40, 25, 23, 23)];
//    [buttonHome setBackgroundImage:[UIImage imageNamed:@"homeLeft02"] forState:UIControlStateNormal];
//    [buttonHome addTarget:self action:@selector(buttonHome:) forControlEvents:UIControlEventTouchUpInside];
//    [self.view addSubview:buttonHome];
    
}
// 头部的 两个按钮
- (void)button:(UIButton *)b{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)buttonHome:(UIButton *)home{
    [self.navigationController popToRootViewControllerAnimated:YES];
}




- (void)setBaseData
{
    _delegate=(AppDelegate*)[[UIApplication sharedApplication]delegate];
    _detailDataManger = [[CoreDateManager alloc] init];
    //取出缓存数据
    _productDetailModel = [_detailDataManger returnProductDetail:self.prodectInfo.iD];
   
    //解析数据
    if (_productDetailModel != nil) {
        _productDetailModel = [self makeDataToModel:_productDetailModel];
    }
    [self getShowPicArry];
    //下载数据，进行判断是否更新
    [self downLoadProductInfo];
}

//获取所有浏览照片的网络地址
- (void)getShowPicArry
{
    _picArry = [NSMutableArray array];
    if (_productDetailModel.pages != nil && _productDetailModel.pages.count != 0) {
        for (BPProductDetailPage *pageModel in _productDetailModel.pages) {
            [_picArry addObject:pageModel.base_img];
        }
    }
}

- (void)setUpNav
{
    //self.title = self.prodectInfo.title;
    NavView *leftNavView = [[NavView alloc] initWithFrame:CGRectMake(0, 0, 70, 40)];
    //leftNavView.navLabel.text = self.leftNavButton;
    leftNavView.delegate = self;
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:leftNavView];
}

- (void)navTap:(UITapGestureRecognizer *)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}

//进入照片选择页
- (void)startDIY
{
    [_showView removeFromSuperview];
    if (_picturePicker == nil) {
        _picturePicker = [[ZYQAssetPickerController alloc] init];
        _picturePicker.assetsFilter = [ALAssetsFilter allPhotos];
        _picturePicker.showEmptyGroups = NO;
    }
//    _picturePicker.navigationBarHidden = YES;

    
    
    
//   
//        UIView *navBar = [[UIView alloc] initWithFrame:CGRectMake(0, 5 * _offHeigt, 100 * _offWidth, 30 * _offHeigt)];
//        
//        self.buttonGame = [[UIButton alloc] initWithFrame:CGRectMake(40 * _offWidth, 3 * _offHeigt, 25 * _offWidth, 25 * _offHeigt)];
//        [self.buttonGame setImage:[UIImage imageNamed:@"返回"] forState:UIControlStateNormal];
//    self.buttonGame.backgroundColor = [UIColor yellowColor];
//        [self.buttonGame addTarget:self action:@selector(buttonGame:) forControlEvents:UIControlEventTouchUpInside];
//        
//        self.buttonNextOne = [[UIButton alloc] initWithFrame:CGRectMake(80 * _offWidth, 3 * _offHeigt, 25 * _offWidth, 25 * _offHeigt)];
//    [self.buttonNextOne setTitle:@"取消" forState:UIControlStateNormal];
//    self.buttonNextOne.backgroundColor = [UIColor redColor];
//        [self.buttonNextOne addTarget:self action:@selector(buttonNextOne:) forControlEvents:UIControlEventTouchUpInside];
//        
//        [navBar addSubview:self.buttonGame];
//        [navBar addSubview:self.buttonNextOne];
//        _picturePicker.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:navBar];
    
    
    
    
    _picturePicker.selectionFilter = [NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary *bindings) {
        if ([[(ALAsset*)evaluatedObject valueForProperty:ALAssetPropertyType] isEqual:ALAssetTypeVideo]) {
            NSTimeInterval duration = [[(ALAsset*)evaluatedObject valueForProperty:ALAssetPropertyDuration] doubleValue];
            return duration >= 5;
        } else {
            return YES;
        }
    }];
    
    [self panduanDeleteImage];
    
    [[_delegate preview] reMoveAllResource];
    [_delegate showPreView];
    [_delegate preview].isAddPic = YES;
    [[_delegate preview] setUpPictureNumber:_productDetailModel.picnum];
    
    [_delegate preview].picnum = self.productDetailModel.picnum;
    [[_delegate preview].readyMakeBtn setTitle:@"开始制作" forState:UIControlStateNormal];
    _picturePicker.vc = self;
    
    [self presentViewController:_picturePicker animated:YES completion:nil];
    [_delegate preview].delegateSelectImage = self;
}

- (void)tabBar:(UITabBarController *)tab{
    [self.navigationController popViewControllerAnimated:YES];
}



- (void)startPintuAction:(ImageAddPreView *)sender
{
    if ([sender.imageassets count] == _productDetailModel.picnum) {
        
        self.meituEditVC = [[BPProductMakeViewController alloc] init];
        self.meituEditVC.productInfo = _productDetailModel;
        self.meituEditVC.alassetArry = sender.imageassets;
        self.meituEditVC.isFirst = YES;
        _delegate.isEdit = NO;
        [_delegate hiddenPreView];
        [_picturePicker dismissViewControllerAnimated:YES completion:^{
            [self.navigationController pushViewController:self.meituEditVC animated:YES];
        }];
        
    }else{
        
#warning 弹出alert框框
        
        // 还需要选择的相片数
        self.Sum = _productDetailModel.picnum - sender.imageassets.count;
        
        NSString *mes = [NSString stringWithFormat:@"制作共需%d张照片,您还需再选%lu张",_productDetailModel.picnum, self.Sum];
        UIAlertView *imageCountWarningalert = [[UIAlertView alloc] initWithTitle:nil
                                                                         message:mes
                                                                        delegate:self
                                                               cancelButtonTitle:nil
                                                               otherButtonTitles:@"确定", nil];
        [imageCountWarningalert show];
        
    }
}




- (void)panduanDeleteImage
{
    NSString *updateDate = [[NSUserDefaults standardUserDefaults] objectForKey:@"updateDate"];
    if (!updateDate) {
        [self writeDate];
    }
    
    NSTimeInterval update = updateDate.doubleValue;
    NSTimeInterval now = [NSDate timeIntervalSinceReferenceDate];
    //8小时一更新
    if ((now - update)>8*60*60) {
        //如果超出八小时就把照片清空
        [self deleteImageCachesImage];
        [self writeDate];
    }
}

- (void)writeDate{
    [[NSUserDefaults standardUserDefaults] setObject:[NSString stringWithFormat:@"%f",[NSDate timeIntervalSinceReferenceDate]] forKey:@"updateDate"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

- (void)deleteImageCachesImage
{
    NSFileManager* fileManager=[NSFileManager defaultManager];
    NSArray *fileList = [[[NSFileManager defaultManager] contentsOfDirectoryAtPath:ImageCahes error:nil] pathsMatchingExtensions:[NSArray arrayWithObject:@"png"]];
    
    for (NSString *imageStr in fileList) {
        NSString *path = [ImageCahes stringByAppendingPathComponent:imageStr];
        BOOL blHave=[[NSFileManager defaultManager] fileExistsAtPath:path];
        if (!blHave) {
           
            return ;
        }else {
            BOOL blDele= [fileManager removeItemAtPath:path error:nil];
            if (blDele) {
                BPLog(@"dele success");
            }else {
                BPLog(@"dele fail");
            }
        }
    }
}

//设置相册collectionview
- (void)setUpdeskCollectionView
{
    
    //设置头部试图
    [self drawUIView];
    _ID = @"cell";
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    _detailModelShow = [[UICollectionView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(_headView.frame), self.view.frame.size.width, self.view.frame.size.height - 40.0f) collectionViewLayout:layout];
    _detailModelShow.delegate = self;
    _detailModelShow.dataSource = self;
    _detailModelShow.showsVerticalScrollIndicator = NO;
    [_detailModelShow registerClass:[BPProductInfoCell class] forCellWithReuseIdentifier:_ID];
    _detailModelShow.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_detailModelShow];
    
    //设置开始制作按钮
    UIButton *startBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    CGFloat btnH = 40.0f;
    startBtn.frame = CGRectMake(0, BPScreenH - btnH, BPScreenW, btnH);
    [startBtn setBackgroundColor:BPGlobaThemeColor];
    [startBtn setTitle:@"开始制作" forState:UIControlStateNormal];
    [startBtn addTarget:self action:@selector(startDIY) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:startBtn];
    
    
//    _ID = @"cell";
//    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
//    _detailModelShow = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 40.0f) collectionViewLayout:layout];
//    _detailModelShow.delegate = self;
//    _detailModelShow.dataSource = self;
//    
//    [_detailModelShow registerClass:[BPProductInfoCell class] forCellWithReuseIdentifier:_ID];
//    _detailModelShow.backgroundColor = [UIColor whiteColor];
//    [self.view addSubview:_detailModelShow];
//    //设置头部试图
//    [self drawUIView];
//    //设置开始制作按钮
//    UIButton *startBtn = [UIButton buttonWithType:UIButtonTypeCustom];
//    CGFloat btnH = 40.0f;
//    startBtn.frame = CGRectMake(0, BPScreenH - btnH, BPScreenW, btnH);
//    [startBtn setBackgroundColor:BPGlobaThemeColor];
//    [startBtn setTitle:@"开始制作" forState:UIControlStateNormal];
//    [startBtn addTarget:self action:@selector(startDIY) forControlEvents:UIControlEventTouchUpInside];
//    [self.view addSubview:startBtn];
}

- (void)drawUIView
{
    
    //初始化头部视图
    _headView = [[BPDetailHeadInfoView alloc] initWithFrame:CGRectMake(0, 0, BPScreenW, 200.0f)];
    [self.view addSubview:_headView];
    if (_productDetailModel != nil) {
        [_headView addProductData:_productDetailModel];
    }
    
//    //初始化头部视图
//    _headView = [[BPDetailHeadInfoView alloc] initWithFrame:CGRectMake(0, 0, BPScreenW, 200.0f)];
//    [_detailModelShow addSubview:_headView];
//    if (_productDetailModel != nil) {
//        [_headView addProductData:_productDetailModel];
//    }
}

#pragma mark <UICollectionViewDataSource>
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    
    return self.productDetailModel.pages.count;
    
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    BPProductInfoCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:_ID forIndexPath:indexPath];
    BPProductDetailPage *pageModel = _productDetailModel.pages[indexPath.row];
    [BPImageTool setUpUIImageView:cell.deskShowImage addNsstringUrl:pageModel.base_img];
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
//    BPProductDetailPage *pageModel = _productDetailModel.pages[indexPath.row];
//    BPImageTool *imageTool = [[BPImageTool alloc] init];
//    
//    [imageTool loadProcessImage:pageModel.base_img withVC:self addPopView:_BigImageView];
    ShowPicture *show = [[ShowPicture alloc] initWithFrame:self.view.bounds];
    _showView = show;
    [_showView setUppageNumAndShowPic:_picArry withCurrentPage:indexPath.row];
    
    [show.startBtn addTarget:self action:@selector(startDIY) forControlEvents:UIControlEventTouchUpInside];
}

//每个collectionview的大小。
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    CGFloat cellW = (BPScreenW - BPStatusCellInset * 3) / 2.0f;
    CGFloat cellH = cellW + 5.0;
    return CGSizeMake(cellW, cellH);
}
//左右两个cell的间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
    return BPStatusCellInset;
}
//上下两个cell的间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
    return BPStatusCellInset;
}

// 整个collectionview离边界的大小
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
//    return UIEdgeInsetsMake(_headView.height + 10, BPStatusCellInset, BPStatusCellInset, BPStatusCellInset);
    return UIEdgeInsetsMake(BPStatusCellInset, BPStatusCellInset, BPStatusCellInset+ CGRectGetHeight(_headView.frame), BPStatusCellInset);
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewDidDisappear:(BOOL)animated
{
    //[MBProgressHUD hideHUD];
}

@end
